import { getOpenId as getOpenIdApi, userReg, userBind } from "@/api/user";

export const baseUrl = "https://test.iteda.com.cn:8088/";
export const appId = "wx75d1618fd15401d7";
export const appSecret = "";
// 登录
const uniLoginNext = () => {
  // 应用配置
  uni.getProvider({
    service: "oauth",
    success: (res) => {
      // console.log(res.provider);
      const { provider } = res;
      // 登录
      uni.login({
        provider,
        success: (loginRes) => {
          console.log(loginRes.code);
          getOpenIdApi({
            data: {
              loginCode: loginRes.code,
              phoneCode: "123123",
              state: "123123",
            },
            callback: ({ openid, session_key }) => {
              uni.setStorageSync(
                "openIdInfo",
                JSON.stringify({
                  openid,
                  session_key,
                })
              );
              setUserReg();
            },
          });
          return;
          if (getOpenId()) {
            setUserReg();
          } else {
            getOpenIdApi({
              query: {
                appid: appId,
                secret: appSecret,
                js_code: loginRes.code,
                grant_type: "authorization_code",
              },
              callback: ({ openid, session_key }) => {
                uni.setStorageSync(
                  "openIdInfo",
                  JSON.stringify({
                    openid,
                    session_key,
                  })
                );
                setUserReg();
              },
            });
          }
        },
        fail(e) {
          console.log("登录", e);
        },
      });
    },
    fail(e) {
      console.log("配置", e);
    },
  });
};
export const setUserReg = (cb = () => {}) => {
  cb({
    id: "马山峰",
    avatar: "/static/images/logo.png",
    personName: "马山峰",
    personPhone: "13312121212",
    local: "",
  });
  return;
  let openid;
  const openIdInfo = uni.getStorageSync("openIdInfo");
  try {
    openid = JSON.parse(openIdInfo).openid;
  } catch (error) {}
  // let pages = getCurrentPages(); //获取加载的页面
  // let currentPage = pages[pages.length - 1]; //获取当前页面的对象
  // let options = currentPage.options; //当前页面url
  // console.log(options);
  if (!openid) {
    return;
  }
  userReg({
    data: {
      openid,
    },
    callback: ({ data }) => {
      const userinfo = deepCopy(data);
      if (!userinfo.personName) {
        userinfo.personName = "微信用户";
      }
      if (!userinfo.avatar) {
        userinfo.avatar =
          "https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132";
      }
      uni.setStorageSync("userInfo", JSON.stringify(userinfo));
      try {
        cb(userinfo);
      } catch (error) {}
    },
    error: () => {
      getUserInfoFn((userinfo) => {
        userBind({
          data: {
            openid,
            personName: userinfo.personName,
            avatar: userinfo.avatar,
          },
        });
        try {
          cb(userinfo);
        } catch (error) {}
      });
    },
    noToast: true,
  });
};
export const uniLogin = () => {
  // 获取用户的当前设置
  uni.getSetting({
    success: (res) => {
      // console.log(res.authSetting);
      if (!res.authSetting["scope.userInfo"]) {
        // 授权
        uni.authorize({
          scope: "scope.userInfo",
          success() {
            uniLoginNext();
          },
          fail(e) {
            console.log("授权", e);
          },
        });
      } else {
        uniLoginNext();
      }
    },
    fail(e) {
      console.log("当前设置", e);
    },
  });
};

// 验证登录
export const judgeLogin = (key) => {
  return true;
  const userInfoStr = uni.getStorageSync("userInfo");
  let userInfo = {};
  try {
    userInfo = JSON.parse(userInfoStr) || {};
  } catch (error) {}
  if (key) {
    if (userInfo["personName"] && userInfo[key]) {
      return true;
    } else {
      return false;
    }
  } else if (userInfo["personName"]) {
    return true;
  }
  uni.showToast({
    icon: "none",
    title: "请先登录",
  });
  setTimeout(() => {
    uni.switchTab({
      url: "/pages/myCenter/index",
    });
  }, 1500);
  return false;
};
// 获取用户信息
export const getUserInfoFn = (cb) => {
  const userInfoStr = uni.getStorageSync("userInfo");
  let userinfo = {};
  try {
    userinfo = JSON.parse(userInfoStr);
    try {
      cb(userinfo);
    } catch (error) {}
  } catch (error) {
    userinfo = {
      avatar:
        "https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132",
      personName: "微信用户",
    };
    uni.setStorageSync("userInfo", JSON.stringify(userinfo));
    try {
      cb(userinfo);
    } catch (error) {}
    // uni.getUserInfo({
    // 	provider: 'weixin',
    // 	success: infoRes => {
    // 		const { userInfo } = infoRes;
    // 		userinfo = {
    // 			personName: userInfo.nickName,
    // 			avatar: userInfo.avatarUrl,
    // 		};
    // 		uni.setStorageSync('userInfo', JSON.stringify(userinfo));
    // 		try {
    // 			cb(userinfo);
    // 		} catch (error) {}
    // 	},
    // });
  }
};
// 获取当前时间/时间戳
export function getTimeNum(j) {
  return j ? new Date() : new Date().valueOf();
}
// 时间戳转换为时间
export function timestampToTime(timestamp) {
  timestamp
    ? (timestamp =
        typeof timestamp == "string"
          ? timeToTimestamp(timestamp)
          : timestamp.valueOf())
    : (timestamp = getTimeNum());

  if (timestamp < 100000000000) {
    timestamp = timestamp * 1000;
  }
  let date = new Date(timestamp);
  let Y = date.getFullYear();
  let M =
    date.getMonth() + 1 < 10
      ? "0" + (date.getMonth() + 1)
      : date.getMonth() + 1;
  let D = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  let h = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
  let m = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
  let s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  let w = date.getDay();
  return {
    Year: Y,
    Month: M,
    Day: D,
    Hour: h,
    Minite: m,
    Second: s,
    Week: w,
  };
}
// 上下午时间
export function transTime(time, en) {
  if (time) {
    let timeArr = time.split(":");
    timeArr[0] =
      Number(timeArr[0]) > 12
        ? en
          ? Number(timeArr[0] - 12) + (en === "small" ? "pm" : "PM")
          : "下午 " + Number(timeArr[0] - 12)
        : en
        ? timeArr[0] + (en === "small" ? "am" : "AM")
        : "上午 " + timeArr[0];
    return timeArr.join(":");
  }
  return time;
}
// 时间格式化
export function TimeTransform(type, addtime, updatetime, hasSecond, showAll) {
  if (!addtime && !updatetime) {
    addtime = getTimeNum();
  }
  let time;
  if (updatetime && updatetime != null && updatetime != "") {
    time = updatetime;
  } else {
    time = addtime;
  }
  if (type) {
    let time_trans, NewTime;
    let j = false;
    // console.log(NewTime)
    type === "差值" || type === "差值1"
      ? null
      : (NewTime = timestampToTime(time));
    switch (type) {
      case "区间":
        let UntilTime = Math.round(
          parseInt(Number(getTimeNum()) / 1000 - Number(time)) / 3600
        );
        if (UntilTime == 0) {
          let UntilT = parseInt(
            (60 * (Number(getTimeNum()) / 1000 - Number(time))) / 3600
          );
          UntilT = UntilT == 0 ? 1 : UntilT;
          time_trans = UntilT + "分钟前";
        } else if (UntilTime < 24) {
          time_trans = UntilTime + "小时前";
        } else if (UntilTime < 48) {
          time_trans = "1天前";
        } else if (UntilTime < 72) {
          time_trans = "2天前";
        } else {
          time_trans =
            NewTime.Year +
            "年" +
            NewTime.Month +
            "月" +
            NewTime.Day +
            "日 " +
            NewTime.Hour +
            ":" +
            NewTime.Minite;
        }
        break;
      case "差值":
        if (!addtime) {
          return "";
        }
        addtime =
          typeof addtime == "string"
            ? timeToTimestamp(addtime)
            : addtime.valueOf();
        updatetime || updatetime === 0
          ? (updatetime =
              typeof updatetime == "string"
                ? timeToTimestamp(updatetime)
                : updatetime.valueOf())
          : null;
        time =
          (updatetime || updatetime === 0 ? updatetime - addtime : addtime) /
          1000;
        time < 0 ? ((time = -time), (j = true)) : null;
        var d = 24 * 60 * 60,
          h = 60 * 60,
          m = 60;
        var day = Math.floor(time / d),
          hour = Math.floor((time % d) / h),
          minite = Math.floor(((time % d) % h) / m),
          second = Math.floor(((time % d) % h) % m);
        // console.log(day,hour,minite,second)
        time_trans = { day, hour, minite, second };
        // time_trans=day?
        // (day+'天'+(hour?(hour+'小时'):'1小时')):
        // ((hour?(hour<10?('0'+hour):hour):'00')+':'+(minite?(minite<10?('0'+minite):minite):'00')+':'+(second?(second<10?('0'+second):second):'01'));
        time_trans =
          (day ? day + "天" : showAll ? "0天" : "") +
          (hour ? hour + "小时" : showAll ? "0小时" : "") +
          (day && !showAll
            ? ""
            : (minite ? minite + "分钟" : showAll ? "0分钟" : "") +
              (hasSecond && !((day || hour) && !showAll)
                ? second
                  ? second + "秒"
                  : showAll
                  ? "0秒"
                  : ""
                : ""));
        j ? (time_trans = "-" + time_trans) : null;
        break;
      case "差值1":
        if (!addtime) {
          return "";
        }
        addtime =
          typeof addtime == "string"
            ? timeToTimestamp(addtime)
            : addtime.valueOf();
        updatetime || updatetime === 0
          ? (updatetime =
              typeof updatetime == "string"
                ? timeToTimestamp(updatetime)
                : updatetime.valueOf())
          : null;
        time = addtime / 1000;
        time < 0 ? ((time = -time), (j = true)) : null;
        var d = 24 * 60 * 60,
          h = 60 * 60,
          m = 60;
        var day = Math.floor(time / d),
          hour = Math.floor((time % d) / h),
          minite = Math.floor(((time % d) % h) / m),
          second = Math.floor(((time % d) % h) % m);
        // console.log(day,hour,minite,second)
        time_trans = { day, hour, minite, second };
        time_trans = day
          ? day + "天" + (hour ? hour + "小时" : "1小时")
          : (hour ? (hour < 10 ? "0" + hour : hour) : "00") +
            ":" +
            (minite ? (minite < 10 ? "0" + minite : minite) : "00") +
            ":" +
            (second ? (second < 10 ? "0" + second : second) : "01");
        j ? (time_trans = "-" + time_trans) : null;
        break;
      default:
        type = type.replace("YYYY", NewTime.Year);
        type = type.replace("yyyy", NewTime.Year);
        type = type.replace("YY", NewTime.Year.toString().slice(2, 4));
        type = type.replace("yy", NewTime.Year.toString().slice(2, 4));
        type = type.replace("MM", NewTime.Month);
        type = type.replace("M", Number(NewTime.Month));
        type = type.replace("DD", NewTime.Day);
        type = type.replace("dd", NewTime.Day);
        type = type.replace("D", Number(NewTime.Day));
        type = type.replace("d", Number(NewTime.Day));
        type = type.replace("hh", NewTime.Hour);
        type = type.replace("HH", NewTime.Hour);
        type = type.replace("mm", NewTime.Minite);
        type = type.replace("ss", NewTime.Second);
        type = type.replace("SS", NewTime.Second);
        let week = ["日", "一", "二", "三", "四", "五", "六"];
        let weekTxt =
          NewTime.Week || NewTime.Week === 0 ? week[Number(NewTime.Week)] : "";
        type = type.replace("W", weekTxt);
        return type;
    }
    return time_trans;
  }
  return addtime;
}
// 时间转换为时间戳
export function timeToTimestamp(value) {
  var time = null;
  if (value !== "" && value !== null) {
    value = value.toString();
    value = value.split("/").join(",");
    value = value.split(" ").join(",");
    value = value.split("-").join(",");
    value = value.split(":").join(",");
    var arr = value.split(",");
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] == null) {
        arr.splice(i, 1);
        i--;
      }
    }
    time = new Date(
      arr[0],
      arr[1] - 1,
      arr[2],
      arr[3] ? arr[3] : 0,
      arr[4] ? arr[4] : 0,
      arr[5] ? arr[5] : 0
    );
    time = time.valueOf();
  }
  return time;
}
// CST转换GMT
export function getTaskTime(strDate) {
  if (null == strDate || "" == strDate) {
    return "";
  }
  var dateStr = strDate.trim().split(" ");
  var strGMT =
    dateStr[0] +
    " " +
    dateStr[1] +
    " " +
    dateStr[2] +
    " " +
    dateStr[5] +
    " " +
    dateStr[3] +
    " GMT+0800";
  var date = new Date(Date.parse(strGMT));
  return date;
}
// 本年第几周
export function getWeekOfYear(today) {
  var today = today ? new Date(timeToTimestamp(today)) : new Date();
  var firstDay = new Date(today.getFullYear(), 0, 1);
  var dayOfWeek = firstDay.getDay();
  var spendDay = 1;
  if (dayOfWeek != 0) {
    spendDay = 7 - dayOfWeek + 1;
  }
  firstDay = new Date(today.getFullYear(), 0, 1 + spendDay);
  var d = Math.ceil((today.valueOf() - firstDay.valueOf()) / 86400000);
  var result = Math.ceil(d / 7);
  return result + 1;
}
// 获取本月天数
export function getDays(n) {
  var today = new Date();
  var d = new Date(
    today.getFullYear(),
    Number(today.getMonth() + 1 + (n ? n : 0)),
    0
  );
  return d.getDate();
}
// 递归获取数据
export function recursion(
  item_,
  id = "id",
  children = "children",
  disabled = "disabled"
) {
  let item = JSON.parse(JSON.stringify(item_));
  let arr = [];
  item && item[disabled] ? null : arr.push(item[id]);
  if (item[children] && item[children].length > 0) {
    for (let i in item[children]) {
      arr = arr.concat(recursion(item[children][i], id, children));
    }
  }
  return arr;
}
// 递归成树
export function toTree(
  arr,
  code = null,
  id = "id",
  children = "children",
  pid = "pid"
) {
  if (arr.length == 0) {
    return [];
  }
  let allTree = arr.filter((v) =>
    !code
      ? v[pid] === undefined ||
        v[pid] === "" ||
        v[pid] === null ||
        v[pid] === 0 ||
        v[pid] === "0"
      : v[pid] == code
  );
  return allTree.map((v) => {
    v.children = toTree(
      arr.filter(
        (v) =>
          !(!code
            ? v[pid] === undefined ||
              v[pid] === "" ||
              v[pid] === null ||
              v[pid] === 0 ||
              v[pid] === "0"
            : v[pid] == code)
      ),
      v[id]
    );
    v[children].length == 0 ? delete v[children] : null;
    return {
      ...v,
    };
  });
}

// 返回价格
export function transformPrice(price, judge, ableZero) {
  if (!price && price !== 0) {
    return "";
  }
  price = price
    .toString()
    .replace(judge === 0 || judge === 1 ? /[^0-9.-]/g : /[^0-9.]/g, "");
  var price1;
  var arr = price.split(".");
  if (arr.length > 1) {
    price1 = arr[0] + "." + arr[1].substr(0, 2);
    // console.log(price1);
  } else {
    price1 = price;
  }
  var setPoint = function (n) {
    // console.log(n.toLocaleString())
    let nString = n.toLocaleString();
    let m = nString.indexOf("-") === 0;
    nString = nString.replace("-", "");
    let nStringArr = nString.split("."),
      nFront = [];
    let nChange = nStringArr[0].split(",").join("");
    for (let i = 0; i < nChange.length / 3; i++) {
      nFront.splice(
        0,
        0,
        nChange.slice(
          nChange.length - (i + 1) * 3 > 0 ? nChange.length - (i + 1) * 3 : 0,
          nChange.length - i * 3
        )
      );
    }
    return (
      (m ? "-" : "") +
      (nFront.join(",") +
        (nFront.length > 0
          ? "." +
            (nStringArr.length > 1 && Number(nStringArr[1])
              ? nStringArr[1].toString().length < 2
                ? nStringArr[1] + "0"
                : nStringArr[1]
              : "00")
          : ""))
    );
  };
  return judge
    ? setPoint(price1)
    : Number(price1) || (Number(price1) === 0 && price1 && ableZero)
    ? Number(price1).toString()
    : "";
}

// 拨打电话
export function callPhone(num) {
  // console.log(num);
  uni.makePhoneCall({
    phoneNumber: num, //仅为示例
  });
}

export const getUrl = ({ url, query = {} }) => {
  let param = Object.keys(query)
    .reduce((arr, k) => {
      return [...arr, `${k}=${query[k]}`];
    }, [])
    .join("&");
  return url + (param ? "?" + param : "");
};

export const deepCopy = (data) => {
  if (data === null || data === undefined) {
    return data;
  } else if (Array.isArray(data)) {
    return data.reduce((arr, item) => {
      arr.push(deepCopy(item));
      return arr;
    }, []);
  } else if (typeof data === "object") {
    return Object.keys(data).reduce((json, k) => {
      json[k] = deepCopy(data[k]);
      return json;
    }, {});
  } else {
    return data;
  }
};
export const getOpenId = () => {
  let openid;
  const openIdInfo = uni.getStorageSync("openIdInfo");
  try {
    openid = JSON.parse(openIdInfo).openid;
  } catch (error) {}
  console.log(openid);
  return openid;
};
export const getDictTxt = (value, arr) => {
  return (arr.find((v) => v.value === value + "") || {}).text || value || "--";
};
export const getDate = (value) => {
  return value ? TimeTransform("YYYY-MM-DD HH:mm:ss", value) : "--";
};
